package de.hauck.rtmidlet;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Displayable;

import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.StockBean;
import de.hauck.rtmidlet.model.StockStore;
import de.hauck.rtmidlet.views.FormConfig;
import de.hauck.rtmidlet.views.FormStockMaintainMenu;

public class FileSystemImportThread implements Runnable {

	private StockStore _myStore;
	// private FormSettingsMenu _formSettings;
	private int _type;
	private Displayable _dble;
	private String _importFile;

	public FileSystemImportThread(int type, String file, StockStore myStore, Displayable dble) {
		_importFile=file;
		_myStore = myStore;
		_dble = dble;
		_type = type;

		new Thread(this).start();
	}

	public FileSystemImportThread(int type, String file, Displayable dble) {
		_importFile = file;
		_dble = dble;
		_type = type;

		new Thread(this).start();
	}

	public void run() {
		if (_type == 0)
			importStocksCSV();
		else if (_type == 1)
			importConfigCSV();
	}

	private void importStocksCSV() {
		try {
			System.out.println("try to import: " + Configuration.importURL);
			FileConnection fc = (FileConnection) Connector.open("file:///"
					+ _importFile, // c.exportURL,
					Connector.READ);
			if (!fc.exists()) {
				throw new IOException("File does not exist");
			}
			DataInputStream is = fc.openDataInputStream();

			try {
				StringBuffer b = new StringBuffer();
				int ch;
				while ((ch = is.read()) != -1) {
					b.append((char) ch);
				}
				parseStockString(b.toString());

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					is.close();
				}
				if (fc != null) {
					fc.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void importConfigCSV() {
		try {
			System.out.println("try to import: " + _importFile);
			FileConnection fc = (FileConnection) Connector.open("file:///"
					+ _importFile, // c.exportURL,
					Connector.READ);
			if (!fc.exists()) {
				throw new IOException("File does not exist");
			}
			DataInputStream is = fc.openDataInputStream();

			try {
				StringBuffer b = new StringBuffer();
				int ch;
				while ((ch = is.read()) != -1) {
					b.append((char) ch);
				}
				parseConfigString(b.toString());
				

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					is.close();
				}
				if (fc != null) {
					fc.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void parseStockString(String str) {
		System.out.println("Parsing: " + str);
		int offset = 0;
		int counter = 0;
		Vector stockVec = new Vector();
		StockBean stock = new StockBean();
		try {
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) == '#') {
					while (str.charAt(i) != '\n') {
						// do nothing
						i++;
					}
					offset = i + 1;
				} else if (str.charAt(i) == ',') {
					String token = str.substring(offset, i);
					stock.setToken(counter, token);
					counter++;
					offset = i + 1;
				} else if (str.charAt(i) == '\n') {
					String token = str.substring(offset, i);
					stock.setToken(counter, token);
					stockVec.addElement(stock);
					counter = 0;
					offset = i + 1;
					stock.printBean();
					stock = new StockBean();
				}
			}
			_myStore.setStocksVector(stockVec);
			((FormStockMaintainMenu) _dble).showImportSuccess();
		} catch (Exception e) {
			RTMidlet.getInstance().alert("Error", e.getMessage(),
					Configuration.ALERT_WAIT_TIME);
			e.printStackTrace();
		}
	}

	private void parseConfigString(String str) {
		System.out.println("Parsing: " + str);
		int offset = 0;
		//int counter = 0;
		String token="";
		Vector chartTypesVec=new Vector();
		Vector chartUrlsVec=new Vector();
		Vector ibQueriesVec = new Vector();
		try {
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) == '#') {
					while (str.charAt(i) != '\n') {
						// do nothing
						i++;
					}
					offset = i + 1;
				} else if (str.charAt(i) == '\n') {
					token = str.substring(offset, i);
					System.out.println(i+" "+offset+": "+ token);
					int index=token.indexOf('=');
					String param="";
					String value="";
					if (index>0) {
						param=token.substring(0,index);
						value=token.substring(index+1,token.length());
					}
					if (param.startsWith("chartType"))
						chartTypesVec.addElement(value);
					else if (param.startsWith("chartUrl"))
						chartUrlsVec.addElement(value);
					else if (param.startsWith("IBQuery")) {
						System.out.println("adding '"+value+"'");
						ibQueriesVec.addElement(value);
						
					} else setValue(param, value); 
					offset = i + 1;				
				} 
			}
			Configuration.CHART_URLS=new String[chartUrlsVec.size()];
			chartUrlsVec.copyInto(Configuration.CHART_URLS);
			String[] chartTypes=new String[chartTypesVec.size()];
			chartTypesVec.copyInto(chartTypes);
			Configuration.setAvailableChartTypes(chartTypes);
			Configuration.IB_QUERIES=new String[ibQueriesVec.size()];
			ibQueriesVec.copyInto(Configuration.IB_QUERIES);
			System.out.println("Setting IBQeuries: "+Configuration.IB_QUERIES.length);
			Configuration.dirtyFlagConfig=true;
			((FormConfig) _dble).showImportSuccess();
		} catch (Exception e) {
			RTMidlet.getInstance().alert("Error", e.getMessage(),
					Configuration.ALERT_WAIT_TIME);
			e.printStackTrace();
		}
	}
	
	private void setValue(String param, String value) {
		System.out.println("Setting "+param+"="+value);
		Configuration.setValue(param, value);	
		
	}

}
